package httpMessage;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;

public class HttpResponse {

	private String mimetype;
	private Calendar date;
	private String statuscode;
	private int size;
	private byte[] data;
	private String httpVersion;
	private String location;

	private SimpleDateFormat format = new SimpleDateFormat(
			"EEE, dd MMM yyyy HH:mm:ss zzz");

	public String getDate() {
		return format.format(date.getTime());
	}

	public String getStatuscode() {
		return statuscode;
	}

	public void setStatuscode(String statuscode) {
		this.statuscode = statuscode;
	}

	public int getSize() {
		return size;
	}

	public void setSize(int size) {
		this.size = size;
	}

	public void setMimetype(String mimetype) {
		this.mimetype = mimetype;
	}

	public String getMimetype() {
		return mimetype;
	}

	public HttpResponse(String response) {
		date = Calendar.getInstance();
		String[] lines = response.split("\r\n");
		String fline[] = lines[0].split(" ");
		statuscode = fline[1];
		setHttpVersion(fline[2]);

		for (int i = 1; i < lines.length; i++) {
			if (lines[i].startsWith("Content-Type:")) {
				mimetype = lines[i].replace("Content-Type: ", "");
			} else if (lines[i].startsWith("Content-Length:")) {

				size = Integer.parseInt(lines[i]
						.replace("Content-Length: ", ""));
			} else if (lines[i].startsWith("Date:")) {
				try {
					date.setTime(format.parse(lines[i].replace("Date: ", "")));
				} catch (ParseException e) {
					e.printStackTrace();
				}
			}
		}
	}

	public HttpResponse(String mimetype, String statuscode, int size) {
		super();
		this.statuscode = statuscode;
		this.mimetype = mimetype;
		this.size = size;
		this.date = Calendar.getInstance();
	}

	public HttpResponse() {
		this.statuscode = "200 OK";
		this.date = Calendar.getInstance();
	}

	@Override
	public String toString() {
		String rString = "";
		rString += "HTTP/1.1 " + statuscode;
		rString += "\r\nDate: " + format.format(date.getTime());
		rString += "\r\nContent-Type: " + mimetype;
		rString += "\r\nContent-Length: " + size;
		rString += "\r\nConnection: close";
		if (getLocation() != null) {
			rString += "\r\nLocation: " + getLocation();
		}
		rString += "\r\n\r\n";
		return rString;
	}

	public byte[] getData() {
		return data;
	}

	public void setData(byte[] data) {
		this.data = data;
	}

	public String getHttpVersion() {
		return httpVersion;
	}

	public void setHttpVersion(String httpVersion) {
		this.httpVersion = httpVersion;
	}

	public String getLocation() {
		return location;
	}

	public void setLocation(String location) {
		this.location = location;
	}

}
